import 'dart:async';

import 'package:audio_session/audio_session.dart';
import 'package:date_format/date_format.dart';
import 'package:dingtalk/core/values/values.dart';
import 'package:flip_card/flip_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:just_audio/just_audio.dart';

class THWorksetScreen extends StatelessWidget {
  const THWorksetScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "MOOSE",
          style: TextStyle(color: Colors.black),
        ),
        actions: [],
      ),
      body: THWorksetBody(),
    );
  }
}

class THWorksetBody extends StatefulWidget {
  @override
  _THWorksetBodyState createState() => _THWorksetBodyState();
}

class _THWorksetBodyState extends State<THWorksetBody>
    with SingleTickerProviderStateMixin {
  GlobalKey<FlipCardState> _flipCardKey = GlobalKey<FlipCardState>();

  AnimationController _animationController;

  bool _show = false;

  Timer _timer;

  String _currentTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);

  String _downTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);

  AudioPlayer _player;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
        vsync: this, duration: Duration(milliseconds: 2000));

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _currentTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
      });
    });

    _player = AudioPlayer();
    _player.playerStateStream.listen((state) {
      switch (state.processingState) {
        case ProcessingState.completed:
          _player.seek(Duration.zero, index: _player.effectiveIndices.first);
          _player.stop();
          break;
        case ProcessingState.idle:
          break;
        case ProcessingState.loading:
          break;
        case ProcessingState.buffering:
          break;
        case ProcessingState.ready:
          break;
      }
    });
    _init();
  }

  _init() async {
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration.music());
    try {
      // await _player.setAudioSource(_playlist);
      // var duration =
      await _player.setAsset('assets/sound/on_duty.mp3');
    } catch (e) {
      // catch load errors: 404, invalid url ...
      print("An error occured $e");
    }
  }

  @override
  void dispose() {
    if (null != _timer && _timer.isActive) {
      _timer.cancel();
    }

    if (null != _animationController) {
      _animationController.dispose();
    }

    if (null != _player) {
      _player.pause();
      _player.dispose();
    }

    super.dispose();
  }

  void _onClick() {
    setState(() {
      _show = true;
    });

    if (_player.playing) {
      return;
    }

    Future.delayed(Duration.zero, () {
      _animationController.repeat();

      Future.delayed(Duration(seconds: 3), () {
        setState(() {
          _downTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
          _animationController.stop();
          _player.play();
          _flipCardKey.currentState.toggleCard();
          _show = false;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: kSize20).copyWith(top: kSize20),
        child: Column(
          children: [_buildFlipCard()],
        ),
      ),
    );
  }

  _buildFlipCard() {
    return FlipCard(
      key: _flipCardKey,
      flipOnTouch: false,
      front: Column(
        children: [
          Card(
            elevation: 0.0,
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: kSize20),
              padding: EdgeInsets.symmetric(vertical: kSize20),
              child: Row(
                children: [
                  Expanded(
                      flex: 4,
                      child: Container(
                        child: Row(
                          children: [
                            ClipOval(
                              child: Container(
                                width: kSize120,
                                height: kSize120,
                                alignment: Alignment.center,
                                color: kTHPrimary,
                                child: Text(
                                  "江景",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: kSize32,
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: kSize20),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    "江景",
                                    style: TextStyle(fontSize: kSize32),
                                  ),
                                  Row(
                                    children: [
                                      Text("MOOSE"),
                                      Padding(
                                        padding: EdgeInsets.only(left: kSize10),
                                        child: Text(
                                          "(查看规则)",
                                          style: TextStyle(color: kTHPrimary),
                                        ),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                  Expanded(
                      flex: 1,
                      child: Container(
                        child: Text(
                          "申请",
                          style: TextStyle(fontSize: kSize32),
                        ),
                      )),
                ],
              ),
            ),
          ),
          Card(
            elevation: 0.0,
            child: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(
                    top: kSize20,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Container(
                        width: kSize250,
                        padding: EdgeInsets.symmetric(
                            vertical: kSize10, horizontal: kSize10),
                        margin: EdgeInsets.only(left: kSize10),
                        decoration: BoxDecoration(
                            color: kTHNormal,
                            borderRadius:
                                BorderRadius.all(Radius.circular(kSize10))),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "上班08:30",
                              style: TextStyle(fontSize: kSize32),
                            ),
                            Row(
                              children: [
                                SvgPicture.asset(
                                  'assets/icons/icon_right.svg',
                                  width: kSize60,
                                  color: kTHPrimary,
                                ),
                                Text(
                                  "08:36已打卡",
                                  style: TextStyle(fontSize: kSize28),
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              vertical: kSize10, horizontal: kSize10),
                          margin:
                              EdgeInsets.only(left: kSize10, right: kSize10),
                          decoration: BoxDecoration(
                              color: kTHNormal,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(kSize10))),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "下班 18:30(弹性)",
                                style: TextStyle(fontSize: kSize32),
                              ),
                              Row(
                                children: [
                                  SvgPicture.asset(
                                    'assets/icons/icon_right.svg',
                                    width: kSize60,
                                    color: kTHPrimary,
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        "08:36已打卡",
                                        style: TextStyle(fontSize: kSize28),
                                      ),
                                      Text(
                                        "更新打卡",
                                        style: TextStyle(
                                            fontSize: kSize28,
                                            color: kTHPrimary),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(top: kSize120),
                  child: Stack(
                    children: [
                      Center(
                        child: GestureDetector(
                          onTap: _onClick,
                          child: ClipOval(
                            child: Container(
                              width: kSize360,
                              height: kSize360,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: kTHPrimary,
                                gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.topCenter,
                                    colors: [
                                      kTHPrimary.withOpacity(0.8),
                                      kTHPrimary.withOpacity(1),
                                    ]),
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    "上班打卡",
                                    style: TextStyle(
                                        color: Colors.white, fontSize: kSize38),
                                  ),
                                  Text(_currentTime,
                                      style: TextStyle(
                                          color: Colors.white, fontSize: kSize38)),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                      Center(
                        child: _show
                            ? RotationTransition(
                                turns: _animationController,
                                child: ClipOval(
                                  child: Container(
                                    width: kSize360,
                                    height: kSize360,
                                    decoration: BoxDecoration(
                                      gradient: SweepGradient(colors: [
                                        Colors.white.withOpacity(0.4),
                                        Colors.white.withOpacity(0.6),
                                      ]),
                                    ),
                                  ),
                                ),
                              )
                            : Container(),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: kSize40,
                    bottom: kSize40,
                  ),
                  child: Text("已进入考勤范围 MOOSE"),
                ),
              ],
            ),
          ),
        ],
      ),
      back: Card(
        elevation: 0.0,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: kSize20, vertical: kSize20),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "下班打卡成功",
                        style: TextStyle(fontSize: kSize32),
                      ),
                      Padding(
                        padding: EdgeInsets.all(kSize10),
                        child: Text(
                          "打卡时间 $_downTime",
                          style: TextStyle(fontSize: kSize32),
                        ),
                      ),
                    ],
                  ),
                  GestureDetector(
                    child: Icon(Icons.close),
                    onTap: () {
                      _flipCardKey.currentState.toggleCard();
                    },
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
